package org.log4jconfig.xml.editor.utils;

import org.apache.commons.lang.StringUtils;
import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList;
import org.eclipse.wst.xml.core.internal.parser.regions.AttributeNameRegion;
import org.eclipse.wst.xml.core.internal.parser.regions.AttributeValueRegion;
import org.eclipse.wst.xml.ui.internal.contentassist.ContentAssistRequest;

@SuppressWarnings("restriction")
public class AttributeInfoLookupUtils {

	/**
	 * Returns the attribute name for which ContentAssist is going to be proposed to the user
	 * @param contentAssistRequest
	 * @return
	 */
	public static String getAttributeName(
			ContentAssistRequest contentAssistRequest) {
		ITextRegion region = contentAssistRequest.getRegion();
		ITextRegionList regions = contentAssistRequest.getDocumentRegion()
				.getRegions();
		while (!(region instanceof AttributeNameRegion)) {
			region = regions.get(regions.indexOf(region) - 1);
		}
		
		return contentAssistRequest.getDocumentRegion().getFullText(region)
				.trim();

	}

	public static String getAttributeMatchValue(
			ContentAssistRequest contentAssistRequest) {
		//FIXME : what if current region is AttributeEqualsRegion (ie, content assistant is called right after the equals sign) ?
		if (contentAssistRequest.getRegion() instanceof AttributeValueRegion) {
			String match = contentAssistRequest.getMatchString();
			if (match != null && match.length() > 0) {
				return StringUtils.replace(match, "\"", "");
			}
		}
		return "";
	}

	public static String getAttributeCurrentValue(
			ContentAssistRequest contentAssistRequest) {
		//FIXME : what if current region is AttributeEqualsRegion (ie, content assistant is called right after the equals sign) ?
		if (contentAssistRequest.getRegion() instanceof AttributeValueRegion) {
			String value = contentAssistRequest.getText();
			// remove heading and trailing double quotes if present...
			if (value != null && value.length() > 0) {
				return StringUtils.replace(value, "\"", "");
			}
		}
		return "";
	}
}
